package com.yangcangclub.message.domain;

import com.alibaba.fastjson.JSON;
import com.yangcangclub.message.bean.MessageParam;
import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.IQueryResult;
import com.gexin.rp.sdk.base.impl.SingleMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.base.payload.APNPayload;
import com.gexin.rp.sdk.exceptions.RequestException;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.TransmissionTemplate;
import com.yangcangclub.commons.utils.JsonUtils;
import com.yangcangclub.commons.utils.StringUtil;
import com.yangcangclub.message.base.MesgBaseDomain;
import com.yangcangclub.system.component.SystemComponent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 推送消息
 */
@Component
public class PushMessage  extends MesgBaseDomain{
    @Autowired
    PullMessage pullMessage;

    @Autowired
    SystemComponent systemComponent;

    private static Logger logger = LoggerFactory.getLogger(PushMessage.class);

    private final static String appId ="3IEkvOnb2w763G5dUxMy3";
    private final static String appKey = "1tbUJzj8Se91aIP9BZhnO1";
    private final static String masterSecret ="IsX2drI4Of8Yzi50zmnUD6";
    private final static String url = "http://sdk.open.api.igexin.com/serviceex";
    private static IGtPush push = new IGtPush(url, appKey, masterSecret);


    /**
     *新增用户通知消息
     *msgType : 新增消息类型,R 回复 ， F 关注 , S 系统消息 , B 收益
     * msgId : 非必填 (文章ID，或关注者ID 收益和系统消息为空或者为0)
     */
    @Async("ApolloAsyncExecutor")
    public void sendPullMesg(int sendUserId,int userId, String msgType, int msgId, String content){
        pullMessage.addPullMesg(sendUserId, userId,  msgType,  msgId,  content);
    }



//
//    /**
//     * platform_type: ANDROID  IOS
//    * msg_token：推送设备token
//     * userId:用户id
//     * title：标题
//     * content：内容
//     * brief：简介
//     * action：通知跳转页面( 0 : 不操作进入main 1：进入消息 2：进入文章 3:私信)
//     * article_uuid：文章uuid
//     * isShow：是否显示通知
//     * isPsuh : 1.投稿通知；2.精选通知；3.投稿审批通知；4.提现通知；5，点赞，6.评论；7.私信
//     */
//    //@Async("ApolloAsyncExecutor")
//    public  void sendMessage(int userId,String title,String content,String brief,
//                             int action,String article_uuid,int isShow,int isPsuh,String userUuid,String userName,String userPhoto) {
//
//        if ( StringUtil.isEmpty(title) || StringUtil.isEmpty(content) || StringUtil.isEmpty(brief))return ;
//
//
//        //推送配置过滤
//        List<Map<String,Integer>> list= systemComponent.queryUserConflist(userId);
//        if(list!=null&&list.size()>0){
//            for(Map map:list){
//                if(isPsuh==(int)map.get("push_type")&&0==(int)map.get("state")){
//                    return;
//                }
//            }
//        }
//
//
//
//        Map<String,Object> map=userComponent.queryUserProfile(null, userId, null);
//        String platformType=map.get("platform_type").toString();
//
//        if(map.get("msgToken")==null)return;
//        String msgToken=map.get("msgToken").toString();
//
//            MessageParam messageParam = new MessageParam();
//            messageParam.setNotifyId(System.currentTimeMillis());
//            messageParam.setTitle(title);
//            messageParam.setContent(content);
//            messageParam.setBrief(brief);
//            messageParam.setAction(action);
//            messageParam.setArticle_uuid(article_uuid);
//            messageParam.setIsShow(isShow);
//            messageParam.setIsPsuh(isPsuh);
//            messageParam.setUser_name(userName);
//            messageParam.setUser_uuid(userUuid);
//            messageParam.setUser_photo(userPhoto);
//
//
//             if("IOS".equalsIgnoreCase(platformType)){
//                this.pushMessageToIOS(msgToken,messageParam);
//            }else{
//                this.pushMessageToAndroid(msgToken,messageParam);
//            }
//        }
//
//    //重载方法
//    //@Async("ApolloAsyncExecutor")
//    public  void sendMessage(int userId,String title,String content,String brief,
//                             int action,String article_uuid,int isShow,int isPsuh) {
//        this.sendMessage( userId, title, content, brief, action, article_uuid, isShow, isPsuh,"","","");
//    }



    private  void  pushMessageToAndroid(String device,MessageParam messageParam) {

                TransmissionTemplate template = new TransmissionTemplate();
                template.setAppId(appId);
                template.setAppkey(appKey);
                template.setTransmissionType(2);// 透传消息设置，1为强制启动应用，客户端接收到消息后就会立即启动应用；2为等待应用启动
                template.setTransmissionContent(JsonUtils.toJsonString((messageParam)));
                SingleMessage message = new SingleMessage();
                message.setOffline(true);
                //离线有效时间，单位为毫秒，可选
                message.setOfflineExpireTime(24 * 3600 * 1000);
                message.setData(template);
                message.setPushNetWorkType(0); //可选。判断是否客户端是否wifi环境下推送，1为在WIFI环境下，0为不限制网络环境。
                Target target = new Target();
                target.setAppId(appId);
                target.setClientId(device);
                IPushResult ret;

            try {
                 ret = push.pushMessageToSingle(message, target);
            }catch(RequestException e){
                e.printStackTrace();
                //重试
                ret = push.pushMessageToSingle(message, target, e.getRequestId());
            }
            if(ret == null){
                logger.error("push message to android fail ,device={},message={}",device,JSON.toJSONString(messageParam));
            }
        }



    private  void pushMessageToIOS(String device,MessageParam messageParam) {

                if(device==null|| !device.contains(","))return;

                APNPayload.DictionaryAlertMsg alertMsg = new APNPayload.DictionaryAlertMsg();
				//alertMsg.setBody(JsonUtils.toJsonString(messageParam));
                alertMsg.setActionLocKey("查看");
                alertMsg.setLocKey(messageParam.getContent());
                alertMsg.addLocArg("loc-args");
                alertMsg.setLaunchImage("launch-image");
				//IOS8.2以上版本支持
				//alertMsg.setTitle(messageParam.getTitle());
				//alertMsg.setTitleLocKey("TitleLocKey");
				//alertMsg.addTitleLocArg("TitleLocArg");

                APNPayload payload = new APNPayload();
                payload.setBadge(1);
                payload.setContentAvailable(1);
                payload.setSound("default");
				//payload.setCategory("由客户端定义");
                payload.addCustomMsg("iamkey", JsonUtils.toJsonString(messageParam));
				//payload.setAlertMsg(new APNPayload.SimpleAlertMsg(messageParam.getTitle()));
                payload.setAlertMsg(alertMsg);

                TransmissionTemplate template = new TransmissionTemplate();
                template.setAppId(appId);
                template.setAppkey(appKey);
                template.setTransmissionContent(JsonUtils.toJsonString(messageParam));
                template.setTransmissionType(2);
                template.setAPNInfo(payload);

                SingleMessage message = new SingleMessage();
                message.setOffline(true);
                //离线有效时间，单位为毫秒，可选
				//message.setOfflineExpireTime(24 * 3600 * 1000);
                message.setData(template);
                message.setPushNetWorkType(0); //可选。判断是否客户端是否wifi环境下推送，1为在WIFI环境下，0为不限制网络环境。

                String cid = device.split(",")[0];
                String devicetoken = device.split(",")[1];

                Target target = new Target();
                target.setAppId(appId);
                target.setClientId(cid);

                IQueryResult abc = push.getClientIdStatus(appId, cid);
                Map<String, Object> cidstatusMap = abc.getResponse();
                String cidstatus = null;
                if(cidstatusMap!=null) {
                    cidstatus = (String)cidstatusMap.get("result");
                }

                boolean isOnline = true;
                if("Offline".equalsIgnoreCase(cidstatus)) {
                    isOnline = false;
                } else if("Online".equalsIgnoreCase(cidstatus)) {
                    isOnline = true;
                }


        //推送
                try {
                    if(isOnline) {
                        push.pushMessageToSingle(message, target);
                    } else {
                         push.pushAPNMessageToSingle(appId, devicetoken, message);
                    }

                }catch(RequestException e) {
                    e.printStackTrace();
                    logger.error("push message to ios fail ,device={},message={},ret={}", device, JSON.toJSONString(messageParam));
                }
        }
    }

